<?php

@$id = $_REQUEST["id"];

@$caixiid = $_REQUEST["caixiid"];
$name = $_REQUEST["name"];
$jiage = $_REQUEST["jiage"];
$img = $_FILES["file"];

/*if (empty($name) || empty($jiage) || empty($img)) {
    exit("菜品信息不足");
}*/


function imgpath($img)
{
    $laststr = strrpos($img["name"], ".");
    $hz = substr($img["name"], $laststr);
    $imgsrc = "upload/" . time() . $hz;
    return $imgsrc;
}

function add($name, $jiage, $img,$caixiid)
{
    $imgsrc = imgpath($img);
    header("Refresh:3;url=cailiebiao.php");
    $upload = move_uploaded_file($img["tmp_name"], $imgsrc);
    if (!$upload) {
        exit("图片上传失败！");
    }

    $pdo = new PDO("mysql:dbname=caipin;host=127.0.0.1;charset=utf8", "root", "root");
    $cpSql = $pdo->prepare("insert into useraa(name,jiage,imgsrc,caixiid) values(:n,:j,:i,:o);");

    $isok = $cpSql->execute(array("n" => $name, "j" => $jiage, "i" => $imgsrc, "o" => $caixiid));
    if ($isok) {
        echo "添加成功！";
    } else {
        echo "添加失败！";
    }
}

function update($id, $name, $jiage, $img,$caixiid)
{
    $imgsrc = imgpath($img);
    header("Refresh:3;url=cailiebiao.php");
    $upload = move_uploaded_file($img["tmp_name"], $imgsrc);
    if (!$upload) {
        exit("图片上传失败！");
    }

    $pdo = new PDO("mysql:dbname=caipin;host=127.0.0.1;charset=utf8", "root", "root");

    $sql = $pdo->prepare("select * from useraa where id=:id");
    $sql->execute(array("id" => $id));
    $jg = $sql->fetch(PDO::FETCH_NAMED);
    if (!empty($jg)) {
        $usql = $pdo->prepare("update useraa set name=:n,jiage=:j,imgsrc=:i,caixiid=:o where id=:id;");
        $isok = $usql->execute(array("n" => $name, "j" => $jiage, "i" => $imgsrc, "id" => $id, "o" => $caixiid));
        if ($isok) {
            echo "修改成功！";
        } else {
            echo "修改失败！";
        }
    }

}

if (empty($id)) {
    add($name, $jiage, $img,$caixiid);
} else {
    update($id, $name, $jiage, $img,$caixiid);
}
